<template>
  <div class="app-pro-basicLayout-content-wrap">
    <div class="app-pro-pages-content">
      <div class="app-pro-table-search">
        <el-form
          :inline="true"
          :model="formInline"
          ref="formInline"
          label-width="80px"
          size="small"
          class="form-flex-item"
        >
          <el-row :gutter="20">
            <el-col :xs="12" :sm="10" :md="8" :lg="6">
              <el-form-item :label="'검색'|language" prop="keyword">
                <el-input v-model="formInline.keyword" :placeholder="'검색어: 이메일, 이름 ,연락처'|language"  @keyup.enter.native="handleSearch"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="6" :sm="6" :md="6" :lg="6">
              <el-form-item>
                <el-button type="primary" size="small" @click="handleSearch">{{'검색'| language}}</el-button>
                <el-button size="small" @click="resetForm('formInline')">{{'초기화'| language}}</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="app-pro-pages-table">
        <div class="main-card">
          <div class="main-table-toolbar">
            <div class="main-table-toolbar-title">
              <div class="main-table-toolbar-title-only">무료결제 관리</div>
            </div>
            <div class="main-table-toolbar-option">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-plus"
                style="margin-right:5px"
                @click="confirmAddPrice"
              >{{'추가'| language}}</el-button>
              <up-File
                style="margin-right:15px"
                :on-success="handleSuccess"
                :before-upload="beforeUpload"
              >
                <i class="el-icon-plus"></i>
                {{'xls로추가'| language}}
              </up-File>
              <a href="/template.xls" download="템플릿 가져 오기.xls" style="margin-right:5px">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-download"
                >
                {{'샘플xls다운'| language}}
                </el-button>
              </a>
              <el-link :underline="false" class="main-table-toolbar-item-icon">
                <el-tooltip class="item" effect="dark" :content="'다운로드'| language" placement="top">
                  <i @click="downloadFile('/api/coupon/index', '무료결제 관리')" class="el-icon-download"></i>
                </el-tooltip>
              </el-link>
            </div>
          </div>
          <div class="main-table-wrapper" style="padding: 0">
            <my-table
              :columns="columns"
              :data="data"
              :loading="loading"
              :pagination="pagination"
              :showIndex="true"
              :showSelection="true"
              :cellStyle="{padding: '6px 0'}"
              :headerCellStyle="{background:'rgba(247, 133, 2, 1)',color:'#fff'}"
              @emitSelection="emitSelection"
              @currentChange="currentChange"
              @sortChange="sortChange"
            >
              <template v-slot:status="slotProps">
                <el-tag
                  effect="dark"
                  size="small"
                  :type="slotProps.callback.row.status_text == '사용불가' ? 'danger' : 'success'"
                >{{slotProps.callback.row.status_text | language}}</el-tag>
              </template>
              <template v-slot:updated_at="slotProps">
                <div v-if="slotProps.callback.row.status == 1">{{slotProps.callback.row.updated_at}}</div>
              </template>
              <template v-slot:effective_at="slotProps">
                <div >{{slotProps.callback.row.start_time}}</div>
                <div>-</div>
                <div >{{slotProps.callback.row.end_time}}</div>
              </template>
              <template v-slot:operation="slotProps">
                <el-button
                  v-if="!slotProps.callback.row.deleted_at"
                  @click.native.prevent="handleEdit(slotProps.callback.row)"
                  type="text"
                >{{'관리'| language}}</el-button>
                <el-divider direction="vertical"></el-divider>
                <el-popconfirm
                  title="삭제하시겠습니까"
                  @onConfirm="handleDelete(slotProps.callback.row.id)"
                  :confirmButtonText="'확인'|language"
                  :cancelButtonText="'취소'|language"
                >
                  <el-button slot="reference" type="text" style="color:#f56c6c">삭제</el-button>
                </el-popconfirm>
              </template>
            </my-table>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      :title="dialogForm.title"
      custom-class="dialog-content"
      :visible.sync="dialogForm.dialogVisible"
      :destroy-on-close="true"
      top="5%"
      width="500px"
    >
      <div class="dialog-body-content">
        <form-page
          :ref-obj.sync="formInfo.ref"
          :data="formInfo.data"
          :field-list="formInfo.fieldList"
          :rules="formInfo.rules"
          :label-width="formInfo.labelWidth"
          :list-type-info="listTypeInfo"
        ></form-page>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogForm.dialogVisible = false">{{'취소'| language}}</el-button>
        <el-button 
          size="small"
          type="primary" 
          :loading="but_loading"
          @click="handleSubmitCoupon">{{'확인'| language}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getDictData } from '@/api/app'
// eslint-disable-next-line no-unused-vars
import { mergeObjOfValue, deepClone, downloadFile } from '@/utils'
import FormPage from '_c/FormPage'
import myTable from '_c/Table'
import upFile from '_c/UploadExcel'
import { getResourceEvents, publicEvents } from '@/mixins'
import * as couponApi from '@/api/coupon/index'
const formInfoData = {
  id: 0,
  code: '',
  target: '',
  email: '',
  name: '',
  phone: '',
  message: '',
  start_time: '',
  end_time: ''
}
export default {
  name: 'coupon',
  data () {
    return {
      but_loading: false,
      formDate: '',
      formInline: {
        keyword: ''
      },
      columns: [{
        label: '상태',
        prop: 'status',
        width: 100,
        slot: 'status'
      }, {
        label: '사업분류코드 ',
        prop: 'code',
        sortable: true,
        width: 150
      }, {
        label: '무료혜택 대상 ',
        prop: 'service',
        sortable: true,
        width: 150
      },
      {
        label: '이메일',
        prop: 'email',
        sortable: true,
        width: 150
      },
      {
        label: '이름',
        prop: 'name',
        sortable: true,
        width: 80
      },
      {
        label: '연락처',
        prop: 'phone',
        sortable: true,
        width: 120
      },
      {
        label: '등록시간',
        prop: 'created_at',
        sortable: true,
        width: 150
      },
      {
        label: '유효시간',
        prop: '',
        sortable: true,
        slot: 'effective_at',
        width: 150
      },
      {
        label: '사용시간',
        prop: '',
        slot: 'updated_at',
        sortable: true,
        width: 150
      }, {
        label: '무료혜택 안내문구',
        prop: 'message',
        sortable: true
      },
      {
        label: '관리',
        prop: '',
        width: 120,
        align: 'left',
        slot: 'operation'
      }],
      data: [],
      pagination: {
        currentPage: 1,
        pageSize: 15
      },
      selectionData: [],
      loading: true,
      dialogForm: {
        dialogVisible: false,
        title: '신규등록'
      },
      listTypeInfo: {
        CoachingService: []
      },
      formInfo: {
        ref: null,
        data: formInfoData,
        fieldList: [
          { label: '사업분류코드', value: 'code', width: '260', type: 'input', className: 'el-form-block', required: true },
          { label: '무료혜택 대상 ', value: 'target', type: 'select', width: '260', className: 'el-form-block', required: true, list: 'CoachingService' },
          { label: '이메일', value: 'email', type: 'input', width: '260', className: 'el-form-block', required: true },
          { label: '이름', value: 'name', type: 'input', width: '260', className: 'el-form-block', required: true, disabled: false },
          { label: '전화', value: 'phone', type: 'input', width: '260', className: 'el-form-block', required: true, disabled: false },
          { label: '시작시간', value: 'start_time', type: 'date', dateType: 'datetime', width: '260', className: 'el-form-block', required: true },
          { label: '마감시간', value: 'end_time', type: 'date', dateType: 'datetime', width: '260', className: 'el-form-block', required: true },
          { label: '무료혜택 안내문구 ', value: 'message', type: 'input', width: '260', className: 'el-form-block', required: true }
        ],
        rules: {},
        labelWidth: '140px'
      },
      sortParams: {}
    }
  },
  components: {
    myTable,
    FormPage,
    upFile
  },
  mixins: [getResourceEvents, publicEvents],
  mounted () {
    this.formInfo.data = deepClone(formInfoData)
    this.getCouponList()
    this.getCoachingService('CoachingService')
    this.initRules()
  },
  methods: {
    initRules () {
      const formInfo = this.formInfo
      formInfo.rules = this.$initRules(formInfo.fieldList)
    },
    beforeUpload (file) {
      this.formDate = new FormData()
      this.formDate.append('file', file)
      couponApi.importCoupon(this.formDate).then((res) => {
        this.$message.success('정상적으로 추가되었습니다.')
        this.getCouponList()
      })
      // const isLt2M = file.size / 1024 / 1024 < 1
      // if (isLt2M) {
      //   return true
      // }
      // this.$message({
      //   message: 'Please do not upload files larger than 2m in size.',
      //   type: 'warning'
      // })
      // return false
    },
    handleSuccess ({ results, header }) {
    },
    getCoachingService (key) {
      getDictData(key).then(res => {
        this.listTypeInfo[key] = res.map(item => {
          return {
            label: item.value,
            value: parseInt(item.idx)
          }
        })
      })
    },
    getCouponList () {
      const data = {
        ...this.formInline,
        ...this.sortParams,
        page: this.pagination.currentPage,
        per: this.pagination.pageSize
      }
      this.loading = true
      couponApi.getCouponList(data).then((res) => {
        this.loading = false
        this.data = res.data
        this.pagination.total = res.meta.pagination.total
      })
    },
    sortChange (val) {
      this.pagination.currentPage = 1
      if (val.order === 'ascending') {
        this.sortParams = {
          sort: 'asc',
          order_by: val.prop
        }
      } else if (val.order === 'descending') {
        this.sortParams = {
          sort: 'desc',
          order_by: val.prop
        }
      } else {
        this.sortParams = {}
      }
      this.getCouponList()
    },
    handleDelete (id) {
      couponApi.deleteCoupon({ id }).then(res => {
        this.$message({
          message: '삭제되었습니다.',
          type: 'success'
        })
        this.getCouponList()
      })
    },
    confirmAddPrice () {
      this.dialogForm.title = '신규등록'
      this.formInfo.data.id = 0
      mergeObjOfValue(this.formInfo.data, formInfoData)
      this.dialogForm.dialogVisible = true
      this.initRules()
    },
    handleSubmitCoupon () {
      if (this.formInfo.data.id === 0) {
        this.formInfo.data.id = null
      }
      switch (this.dialogForm.title) {
        case '신규등록':
          this.formInfo.ref.validate((valid) => {
            if (valid) {
              this.but_loading = true
              couponApi.createCoupon(this.formInfo.data).then(res => {
                this.$message({
                  message: '정상적으로 추가되었습니다.',
                  type: 'success'
                })
                this.but_loading = false
                this.getCouponList()
                this.dialogForm.dialogVisible = false
              }).catch((value) => {
                this.but_loading = false
              })
            }
          })
          break
        case '관리':
          this.formInfo.ref.validate((valid) => {
            if (valid) {
              this.but_loading = true
              couponApi.updateCoupon(this.formInfo.data).then(res => {
                this.$message({
                  message: '반영이 완료되었습니다.',
                  type: 'success'
                })
                this.but_loading = false
                this.getCouponList()
                this.dialogForm.dialogVisible = false
              }).catch((value) => {
                this.but_loading = false
              })
            }
          })
          break
      }
    },
    handleEdit (rowData) {
      this.dialogForm.title = '관리'
      this.formInfo.data.id = rowData.id
      mergeObjOfValue(this.formInfo.data, rowData)
      this.dialogForm.dialogVisible = true
      this.initRules()
    },
    handleSearch () {
      this.pagination.currentPage = 1
      this.getCouponList()
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.getCouponList()
    },
    emitSelection (val) {
      this.selectionData = val
    },
    currentChange (val) {
      this.pagination.currentPage = val
      this.getCouponList()
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
